package com.nineclock.document.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nineclock.common.entity.PageResult;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.document.dto.DocCollaborationsDto;
import com.nineclock.document.dto.DocumentUserDTO;
import com.nineclock.document.mapper.DocCollaborationsMapper;
import com.nineclock.document.pojo.DocCollaborations;
import com.nineclock.document.service.DocCollaborationsService;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.feign.SysCompanyUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class DocCollaborationsServiceImpl implements DocCollaborationsService {

    @Autowired(required = false)
    private DocCollaborationsMapper collaborationsMapper;

    @Autowired
    private SysCompanyUserFeign companyUserFeign;


    @Override
    public PageResult pagingCollaborations(Long id, Integer page, Integer pageSize) {
        // 分页查询文档协作者表
        LambdaQueryWrapper<DocCollaborations> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DocCollaborations::getFileId, id);

        // 定义分页对象，参数1-当前页，参数2-页大小
        IPage<DocCollaborations> ipage = new Page<>(page, pageSize);
        ipage = collaborationsMapper.selectPage(ipage, wrapper);

        // 获取当前页的数据
        List<DocCollaborations> collaborationsList = ipage.getRecords();

        if (!CollectionUtils.isEmpty(collaborationsList)) {

            List<DocumentUserDTO> documentUserDTOS = collaborationsList.stream().map(docCollaborations -> {
                DocumentUserDTO documentUserDTO = new DocumentUserDTO();
                documentUserDTO.setId(docCollaborations.getCollaborationId());

                // 调用系统微服务接口，根据协作者id查询员工信息
                SysCompanyUserDTO companyUserDTO = companyUserFeign.queryCompanyUserById(documentUserDTO.getId()).getData();
                if (companyUserDTO != null) {
                    documentUserDTO.setUserName(companyUserDTO.getUserName());
                }
                return documentUserDTO;

            }).collect(Collectors.toList());

            return new PageResult(ipage.getTotal(), ipage.getPages(), documentUserDTOS);
        }
        return new PageResult(ipage.getTotal(), ipage.getPages(), null);
    }
}
